﻿using Microsoft.EntityFrameworkCore;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dqs_DAL
{
	public class Admin_DAL
	{


		#region 管理员管理
		/// <summary>
		/// 插入管理员信息
		/// </summary>
		/// <param name="admins"></param>
		/// <returns></returns>
		public bool InsertAdminInfo(AdminInfo admins)
		{
			using (MyDbContext db = new MyDbContext())
			{
				if (admins == null)
					return false;
				db.Admins.Add(admins);
				db.SaveChanges();
			}
			return true;
		}

		/// <summary>
		/// 通过Id修改管理员信息
		/// </summary>
		/// <param name="admin"></param>
		public bool UpdateAdminInfoById(AdminInfo adminNew)
		{
			using (MyDbContext db = new MyDbContext())
			{
				var adminOld = db.Admins.Where(x => x.Id == adminNew.Id).FirstOrDefault();
				if (adminOld == null)
				{
					return false;
				}
				adminOld.FullName = adminNew.FullName;
				adminOld.UserName = adminNew.UserName;
				adminOld.Password = adminNew.Password;
				adminOld.Phone = adminNew.Phone;

				db.SaveChanges();
			}
			return true;
		}

		/// <summary>
		/// 通过Id删除管理员信息
		/// </summary>
		/// <param name="teacherId"></param>
		/// <returns></returns>
		public bool DeleteAdminInfoById(int adminId)
		{
			using (MyDbContext db = new MyDbContext())
			{
				var admin = db.Admins.FirstOrDefault(s => s.Id == adminId);
				if (admin == null)
				{
					return false;
				}
				db.Admins.Remove(admin);
				db.SaveChanges();
			}
			return true;
		}

		/// <summary>
		/// 查询所有管理员信息
		/// </summary>
		/// <returns></returns>
		public List<AdminInfo> QueryAdminInfo()
		{
			using (MyDbContext db = new MyDbContext())
			{
				var admins = db.Admins;
				List<AdminInfo> list = new List<AdminInfo>();
				foreach (var temp in admins)
				{
					AdminInfo admin = new AdminInfo();
					admin.Id = temp.Id;
					admin.FullName = temp.FullName;
					admin.UserName = temp.UserName;
					admin.Password = temp.Password;
					admin.DelFlag = temp.DelFlag;
					admin.Phone = temp.Phone;
					admin.Role = temp.Role;
					list.Add(admin);
				}
				
				return list;
			}
		}

		/// <summary>
		/// 管理员登录
		/// </summary>
		/// <param name="name"></param>
		/// <param name="pwd"></param>
		/// <returns></returns>
		public AdminInfo IsLoginOfAdmin(string name, string pwd)
		{
			using (MyDbContext db = new MyDbContext())
			{
				var result = db.Admins.Where(a=>a.UserName == name).Where(a=>a.Password == pwd).FirstOrDefault();
				if (result != null)
				{
					return result;
				}

				return null!;
			}
		}



		#endregion



	}
}
